package cse.luanvan;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.view.MotionEvent;

public class DrawableMapOverlay extends Overlay {

	private final GeoPoint geoPoint;
	private final GeoPoint geoPoint1;
	private final Context context;

	public DrawableMapOverlay(Context ctx, GeoPoint geoPoint, GeoPoint geoPoint1) {
		super(ctx);
		this.geoPoint = geoPoint;
		this.context = ctx;
		// this.drawable = drawable;
		this.geoPoint1 = geoPoint1;
	}

	@Override
	public boolean onLongPress(MotionEvent e, MapView mapView) {
		// TODO Auto-generated method stub
		// Toast.makeText(context, "hello", Toast.LENGTH_LONG).show();
		return super.onLongPress(e, mapView);
	}

	@Override
	protected void draw(Canvas canvas, MapView mapview, boolean shadow) {
		// TODO Auto-generated method stub
		Point screentPoint = new Point();
		Point point1 = new Point();
		mapview.getProjection().toPixels(geoPoint, screentPoint);
		mapview.getProjection().toPixels(geoPoint1, point1);

		double north_south = geoPoint1.getLatitudeE6()
				- geoPoint.getLatitudeE6();
		double east_west = geoPoint1.getLongitudeE6()
				- geoPoint.getLongitudeE6();
		int angle = (int) (Math.atan2(east_west / 1E6, north_south / 1E6)
				/ Math.PI * 180.0);
		if (north_south != 0 || east_west != 0) {

			if (angle < 0)
				angle += 360;
			// if(angle==0) angle=180;
			if (angle % 3 != 0) {
				if (angle % 3 == 1)
					angle -= 1;
				else
					angle += 1;
			}

			String uri = "arrow_" + String.valueOf(angle);
			int imageResource = context.getResources().getIdentifier(uri,
					"drawable", context.getPackageName());
			Bitmap arrow = BitmapFactory.decodeResource(context.getResources(),
					imageResource);
			canvas.drawBitmap(arrow,
					(screentPoint.x + point1.x) / 2 - arrow.getWidth() / 2,
					(screentPoint.y + point1.y) / 2 - arrow.getHeight() / 2,
					null);
		}
	}

}
